package org.internna.ossmoney.model;

import java.util.Set;
import java.util.List;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.Collections;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;
import javax.validation.constraints.Size;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.springframework.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.roo.addon.jpa.entity.RooJpaEntity;
import org.springframework.roo.addon.serializable.RooSerializable;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;

@RooJavaBean
@RooToString
@RooJpaEntity
@RooSerializable
@RooJpaActiveRecord
public class Dashboard extends AbstractEntity {

    private static final long serialVersionUID = 5335357059487509320L;

    @NotNull
    @Value("3")
    @Min(1L)
    @Max(5L)
    private Integer columns;

    @Size(max = 25)
    @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "dashboard")
    private Set<Widget> widgets = new HashSet<Widget>();

    /**
     * Adds a widget to the dashboard.
     *
     * @param widget any
     */
    public void addWidget(Widget widget) {
    	if (widget != null) {
    		if (widgets == null) {
    			widgets = new HashSet<Widget>();
    		}
    		widgets.add(widget);
    		widget.setDashboard(this);
    	}
    }

    /**
     * Orders widgets in a dashboard matrix.
     *
     * @return a non null non modifiable collection
     */
    public List<Set<Widget>> getWidgetsByColumn() {
    	List<Set<Widget>> widgetsByColumn = new ArrayList<Set<Widget>>(columns);
    	widgetsByColumn.add(new TreeSet<Widget>());
    	widgetsByColumn.add(new TreeSet<Widget>());
    	widgetsByColumn.add(new TreeSet<Widget>());
    	if (!CollectionUtils.isEmpty(widgets)) {
    		for (Widget widget : widgets) {
    			widgetsByColumn.get(widget.getDashboardColumn() - 1).add(widget);
    		}
    	}
    	return Collections.unmodifiableList(widgetsByColumn);
    }

    /**
     * Dashboards cannot be removed (NOP).
     */
    public void remove() {
        return;
    }

}
